<template>
  <div id="UploadPunish">
    <el-breadcrumb
      separator="/"
      style="padding-left: 10px; padding-bottom: 10px; font-size: 12px"
    >
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>处分上传</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" shadow="hover">
      <el-form
        :inline="true"
        :model="queryMap"
        size="small"
        class="demo-form-inline"
      >
        <el-form-item label="处分类型" label-width="75px">
          <el-select
            v-model="queryMap.punishId"
            placeholder="请选择处分类型"
            clearable
          >
            <el-option
              v-for="item in punishList"
              :key="item.punishId"
              :label="item.punishName"
              :value="item.punishId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="学生姓名" label-width="75px">
          <el-input
            v-model="queryMap.stuName"
            placeholder="请数据学生姓名"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            @click="search"
            type="primary"
            icon="el-icon-search"
            :loading="loading"
            round
            >查询</el-button
          >
          <el-button
            @click="stuPunishShow = true"
            type="warning"
            icon="el-icon-plus"
            :loading="loading"
            round
            >添加处分</el-button
          >
          <el-button
            @click="drawer = true"
            type="success"
            icon="el-icon-search"
            :loading="loading"
            round
            >处分类型</el-button
          >
        </el-form-item>
        <el-form-item label="">
          <!--limit:最大上传数，on-exceed：超过最大上传数量时的操作  -->
          <el-upload
            class="upload-demo"
            icon="el-icon-upload2"
            action=""
            :on-change="handleChange"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="limitUpload"
            accept="application/vnd.openxmlformats-    
        officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
            :auto-upload="false"
          >
           <el-tooltip class="item" effect="dark" content="处分导入入口" placement="top-start">
            <el-button size="small" type="info" round icon="el-icon-upload2"
              >处分导入</el-button
            >
           </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <template>
        <el-table
          :data="stuPunishList"
          border
          stripe
          size="small"
          style="width: 100%; margin-top: 5px"
        >
          <el-table-column
            prop="stuNum"
            label="学号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="className"
            label="班级"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="stuName"
            label="学生姓名"
            align="center"
          ></el-table-column>
          <el-table-column prop="punishTime" label="创建时间" align="center"
            ><template slot-scope="scope">{{
              scope.row.punishTime | dateFormat
            }}</template></el-table-column
          >
          <el-table-column
            prop="punishName"
            label="处分"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="score"
            label="扣分"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                :loading="loading"
                @click="removeCurrentStuPunish(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <el-pagination
        style="margin-top: 10px"
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="this.queryMap.page"
        :page-sizes="[10, 50, 100]"
        :page-size="this.queryMap.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>
    <el-dialog title="处分类型" :visible.sync="punishShow" width="300px">
      <el-form :model="currentPunish" align="center">
        <el-form-item label="处分名称" label-width="75px">
          <el-input
            v-model="currentPunish.punishName"
            autocomplete="off"
            width="15px"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          type="primary"
          @click="insertCurrentPunish"
          :loading="loading"
          >确 定</el-button
        >
        <el-button @click="punishShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog title="学生处分" :visible.sync="stuPunishShow" width="400px">
      <el-form :model="stuPunish" align="center">
        <el-form-item label="学生" label-width="75px">
          <el-select
            v-model="stuPunish.stuId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入学生姓名"
            :remote-method="getStuList"
            :loading="loading"
          >
            <el-option
              v-for="item in stuList"
              :key="item.userId"
              :label="item.username"
              :value="item.userId"
            >
              <span style="float: left">{{ item.username }}</span>
              <span style="float: right; color: #8492a6; font-size: 12px"
                >{{ item.className }}/{{ item.num }}</span
              >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="处分类型" label-width="75px">
          <el-select v-model="stuPunish.punishId" placeholder="请选择处分类型">
            <el-option
              v-for="item in punishList"
              :key="item.punishId"
              :label="item.punishName"
              :value="item.punishId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分数" label-width="75px">
          <el-input
            v-model="stuPunish.score"
            placeholder="请输入"
            style="width: 220px"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="insertStuPunish" :loading="loading"
          >确 定</el-button
        >
        <el-button @click="stuPunishShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <el-drawer title="处分类型" :visible.sync="drawer" direction="rtl">
      <el-form>
        <el-form-item>
          <el-button
            style="margin-left: 40%"
            @click="(drawer = false), (currentPunish = {}), (punishShow = true)"
            type="primary"
            icon="el-icon-plus"
            :loading="loading"
            size="mini"
            round
            >添加类型</el-button
          >
        </el-form-item></el-form
      >
      <el-table
        :data="punishList"
        border
        stripe
        size="small"
        style="margin-top: 5px"
      >
        <el-table-column
          prop="punishName"
          label="处分名称"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="text"
              icon="el-icon-delete"
              size="mini"
              :loading="loading"
              @click="removePunishType(scope.row.punishId)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-drawer>
  </div>
</template>
<script>
import { mapState } from "vuex";
import {
  queryStuPunish,
  savePunish,
  queryStuByPage,
  queryPunishTypes,
  saveCurrentStuPunish,
  delCurrentStuPunish,
  delPunishType,
  importPunishScore,
} from "api/api";
export default {
  computed: {
    ...mapState(["userInfo"]),
  },
  data() {
    return {
      queryMap: { page: 1, size: 10 },
      loading: false,
      punishShow: false,
      stuPunishShow: false,
      punishList: [],
      stuPunish: {},
      currentPunish: {},
      stuPunishList: [],
      total: 0,
      stuList: [],
      drawer: false,
      limitUpload: 2,
    };
  },
  methods: {
    //改变页码
    handleSizeChange(newSize) {
      this.queryMap.size = newSize;
      this.getStuPunishList();
    },
    //翻页
    handleCurrentChange(current) {
      this.queryMap.page = current;
      this.getStuPunishList();
    },
    //新增处分类型
    insertCurrentPunish() {
      savePunish(this.userInfo.sessionId, this.currentPunish).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.$message({
            type: "success",
            message: "新增成功！",
          });
          this.punishShow = false;
          this.drawer = true;
          this.getPunishType();
        }
      });
    },
    //获取学生列表
    getStuList(query) {
      this.stuList = [];
      let queryMap = {};
      queryMap.stuName = query;
      queryStuByPage(this.userInfo.sessionId, queryMap).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.stuList = res.data.rows;
        }
      });
    },
    //获取处分类型
    getPunishType() {
      queryPunishTypes(this.userInfo.sessionId).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.punishList = res.data;
        }
      });
    },
    //新增学生处分
    insertStuPunish() {
      saveCurrentStuPunish(this.userInfo.sessionId, this.stuPunish).then(
        (res) => {
          if (!res.flag) {
            this.$message.error(res.message);
          } else {
            this.$message({
              type: "success",
              message: "保存成功！",
            });
            this.stuPunishShow = false;
            this.getStuPunishList();
          }
        }
      );
    },
    //查询所有学生的处分信息
    getStuPunishList() {
      queryStuPunish(this.userInfo.sessionId, this.queryMap).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.stuPunishList = res.data.rows;
          this.total = res.data.total;
        }
      });
    },
    //查询
    search() {
      this.loading = true;
      queryStuPunish(this.userInfo.sessionId, this.queryMap).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
          this.loading = false;
          this.stuPunishList = [];
        } else {
          this.stuPunishList = res.data.rows;
          this.total = res.data.total;
          this.loading = false;
        }
      });
    },
    //删除当前学生处分信息
    async removeCurrentStuPunish(row) {
      var res = await this.$confirm(
        "此操作将删除该学生的处分，是否继续？",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch(() => {
        this.$message({
          type: "info",
          message: "已取消操作！",
        });
      });
      if (res == "confirm") {
        delCurrentStuPunish(
          this.userInfo.sessionId,
          row.stuId,
          row.punishId,
          row.id
        ).then((res) => {
          if (!res.flag) {
            this.$message.error(res.message);
          } else {
            this.$message({
              type: "success",
              message: "删除成功！",
            });
            this.getStuPunishList();
          }
        });
      }
    },
    removePunishType(punishTypeId) {
      delPunishType(punishTypeId).then((res) => {
        if (!res.flag) {
          this.$message.error(res.message);
        } else {
          this.$message({
            type: "success",
            message: "删除成功！",
          });
          this.getPunishType();
        }
      });
    },
    //上传文件时处理方法
    async handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (this.fileTemp) {
        if (
          this.fileTemp.type ==
            "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" ||
          this.fileTemp.type == "application/vnd.ms-excel"
        ) {
          await this.importPunishList(this.fileTemp);
        } else {
          this.$message({
            type: "warning",
            message: "附件格式错误，请删除后重新上传！",
          });
        }
      } else {
        this.$message({
          type: "warning",
          message: "请上传附件！",
        });
      }
    },
    //超出最大上传文件数量时的处理方法
    async handleExceed() {
      this.$message({
        type: "warning",
        message: "超出最大上传文件数量的限制！",
      });
      return;
    },
    //移除文件的操作方法
    async handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    async importPunishList(obj) {
      let _this = this;
      let inputDOM = this.$refs.inputer;
      // 通过DOM取文件数据
      this.file = event.currentTarget.files[0];
      var rABS = false; //是否将文件读取为二进制字符串
      var f = this.file;
      var reader = new FileReader();
      //if (!FileReader.prototype.readAsBinaryString) {
      FileReader.prototype.readAsBinaryString = function (f) {
        var binary = "";
        var rABS = false; //是否将文件读取为二进制字符串
        var pt = this;
        var wb; //读取完成的数据
        var outdata;
        var reader = new FileReader();
        reader.onload = (e) => {
          var bytes = new Uint8Array(reader.result);
          var length = bytes.byteLength;
          for (var i = 0; i < length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
          //此处引入，用于解析excel
          var XLSX = require("xlsx");
          if (rABS) {
            wb = XLSX.read(btoa(fixdata(binary)), {
              //手动转化
              type: "base64",
            });
          } else {
            wb = XLSX.read(binary, {
              type: "binary",
            });
          }
          outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]);
          //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
          //此处可对数据进行处理
          let arr = [];
          console.log(outdata);
          outdata.map((v) => {
            let obj = {};
            obj.num = v["学号"];
            obj.username = v["姓名"];
            obj.className = v["班级"];
            obj.leave = v["早退次数"];
            obj.absence = v["旷课次数"];
            obj.late = v["迟到次数"];
            arr.push(obj);
          });
          _this.importData(arr);
        };
        reader.readAsArrayBuffer(f);
      };
      if (rABS) {
        reader.readAsArrayBuffer(f);
      } else {
        reader.readAsBinaryString(f);
      }
    },
    importData(data) {
      this.loading = true;
      importPunishScore(data)
        .then((res) => {
          if (!res.flag) {
            this.$message.error(res.message+res.data);
            this.loading = false;
          } else {
            this.$message({
              type: "success",
              message: "导入成功！",
            });
            this.loading = true;
            this.search();
          }
        })
    },
  },
  mounted() {
    this.getStuPunishList();
    this.getPunishType();
  },
};
</script>